﻿using MongoDB.Bson.Serialization.Attributes;

namespace Devonline.Database.MongoDB.Models;

/// <summary>
/// MongoDB 数据库模型基础密文基类
/// </summary>
public class CipherMongoModelWithCreate : MongoModelWithCreate, IDataCipher, IMongoModel, IViewModel, IEntitySet, IEntitySetWithCreate
{
    /// <summary>
    /// 数据版本号, 用于给数据增加一个变量, 在计算 Hash 值时增加不确定因素
    /// </summary>
    [BsonElement("version")]
    public virtual string Version { get; set; } = KeyGenerator.GetStringKey();
    /// <summary>
    /// 数据 Hash 值, 用于确认数据是否被篡改
    /// </summary>
    [BsonElement("hashCode")]
    public virtual string HashCode { get; set; } = null!;
    /// <summary>
    /// 数据密文, 数据被用户数据密钥加密后的结果
    /// </summary>
    [BsonElement("ciphertext")]
    public virtual string Ciphertext { get; set; } = null!;

    /// <summary>
    /// 计算并设置 hash code
    /// </summary>
    public virtual void SetHashCode() => HashCode = this.ToKeyValuePairs().Where(x => x.Key != nameof(HashCode).ToCamelCase() && x.Key != nameof(Ciphertext).ToCamelCase()).OrderBy(x => x.Key).ToString(AppSettings.DEFAULT_URL_OUTER_SPLITER, AppSettings.DEFAULT_URL_INNER_SPLITER).GetHashString();
}